package com.atguigu.eduservice.service.impl;

import com.aiguigu.commonutils.ResultCode;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.frontvo.CourseQueryVo;
import com.atguigu.eduservice.entity.frontvo.CourseWebVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Y丶HS练习谷粒商城
 * @since 2022-09-24
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {


    @Resource
    private EduCourseDescriptionService eduCourseDescriptionService;

    @Resource
    private EduChapterService eduChapterService;

    @Resource
    private EduVideoService eduVideoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveEntity(CourseInfoVo courseInfoVo) {
        // 1.向课程表啊添加课程信息
        EduCourse eduCourse = new EduCourse();
        // copy属性
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert <= 0) {
            throw new GuLiException(ResultCode.ERROR, "添加课程信息失败");
        }
        String cid = eduCourse.getId();
        //2. 向课程简介表添加简介
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        // copy属性
        BeanUtils.copyProperties(courseInfoVo, eduCourseDescription);
        // 设置id
        eduCourseDescription.setId(cid);
        eduCourseDescriptionService.save(eduCourseDescription);

        return cid;
    }

    @Override
    public CourseInfoVo getEntityById(String id) {
        // 查询课程
        EduCourse course = this.getById(id);
        if (Objects.isNull(course)) {
            throw new GuLiException(ResultCode.ERROR, "根据课程id未找到该课程");
        }
        // 组转返回
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoVo);
        // 查询课程描述实体
        courseInfoVo.setDescription(eduCourseDescriptionService.getById(id).getDescription());
        return courseInfoVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String updateEntity(CourseInfoVo courseInfoVo) {
        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, course);
        boolean flag = this.updateById(course);
        if (!flag) {
            throw new GuLiException(ResultCode.ERROR, "修改课程信息失败");
        }
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo, eduCourseDescription);
        flag = eduCourseDescriptionService.updateById(eduCourseDescription);
        if (!flag) {
            throw new GuLiException(ResultCode.ERROR, "修改课程描述信息失败");
        }
        return course.getId();
    }

    @Override
    public CoursePublishVo findCoursePublishVoById(String id) {
        return baseMapper.findCoursePublishVoById(id);
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteEntityById(String courseId) {
        // 删除课程
        this.removeById(courseId);
        // 删除描述
        eduCourseDescriptionService.removeById(courseId);
        // 删除章节
        eduChapterService.deleteEntityByCourseId(courseId);
        // 删除小节
        eduVideoService.deleteEntityByCourseId(courseId);


        return true;
    }

    @Cacheable(key = "'course'", value = "selectCourse")
    @Override
    public List<EduCourse> listByLimit4() {
        LambdaQueryWrapper<EduCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(EduCourse::getId).last( "limit 8");
        List<EduCourse> selectCourse = this.list(queryWrapper);
        return selectCourse;
    }

    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> eduCoursePage, CourseQueryVo courseQuery) {
        // 其他条件
        LambdaQueryWrapper<EduCourse> queryWrapper = new LambdaQueryWrapper();

        // 条件拼接判断
        if (Objects.nonNull(courseQuery)) {
            // 一级分类
            String subjectParentId = courseQuery.getSubjectParentId();
            // 二级分类
            String subjectId = courseQuery.getSubjectId();
            // 关注度排序
            String buyCountSort = courseQuery.getBuyCountSort();
            // 创建时间排序
            String gmtCreateSort = courseQuery.getGmtCreateSort();
            // 价格排序
            String priceSort = courseQuery.getPriceSort();
//            String title = courseQuery.getTitle();
            queryWrapper
//                    .like(StringUtils.hasLength(title), EduCourse::getTitle, title)
                    .eq(StringUtils.hasLength(subjectParentId), EduCourse::getSubjectParentId, subjectParentId)
                    .eq(StringUtils.hasLength(subjectId), EduCourse::getSubjectId, subjectId)
                    .orderByDesc(StringUtils.hasLength(buyCountSort),EduCourse::getBuyCount)
                    .orderByDesc(StringUtils.hasLength(gmtCreateSort),EduCourse::getGmtCreate)
                    .orderByDesc(StringUtils.hasLength(priceSort),EduCourse::getPrice)
            ;

        }
        this.page(eduCoursePage, queryWrapper);
        // 取出结果
        List records = eduCoursePage.getRecords();
        // 当前页
        long current = eduCoursePage.getCurrent();
        // 页大小
        long pages = eduCoursePage.getPages();
        // 当前页条数
        long total = eduCoursePage.getTotal();
        // 总条数
        long size = eduCoursePage.getSize();
        // 是否有下一页
        boolean hasNext = eduCoursePage.hasNext();
        // 是否有上一页
        boolean hasPrevious = eduCoursePage.hasPrevious();
        Map<String,Object> map = new HashMap<>(7);
        map.put("info",records);
        map.put("current",current);
        map.put("pages",pages);
        map.put("total",total);
        map.put("hasNext",hasNext);
        map.put("hasPrevious",hasPrevious);
        map.put("size",size);
        return map;
    }

    @Override
    public CourseWebVo getBaseCourseById(String courseId) {


        return baseMapper.getBaseCourseById(courseId);
    }
}
